/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lt.cj.core.filters;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.lexer.Page;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.ScriptTag;
import org.htmlparser.util.DefaultParserFeedback;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.lt.cj.config.entities.ConfigModel;
import org.lt.cj.core.utils.HttpAccesser;

/*
 * @author luohong
 */
public class HierPathFilter {

    private Parser parser;                                                      //定义解析器
    private String contentFilted;                                               //过滤后返还的内容
    private ConfigModel configModel;
    private String parseText;                                                   //要解析的内容

    private boolean createParser(String inputHTML) {

        Lexer mLexer = new Lexer(new Page(inputHTML));
        parser = new Parser(mLexer, new DefaultParserFeedback(DefaultParserFeedback.QUIET));
        try {
            parser.setEncoding(configModel.getPageEncoding());
            return true;
        } catch (ParserException e) {
            e.printStackTrace();
        }
        return false;
    }

    public HierPathFilter(String htmlText, String encoding) {
        this.parseText = htmlText;
        Lexer mLexer = new Lexer(new Page(htmlText));
        parser = new Parser(mLexer, new DefaultParserFeedback(DefaultParserFeedback.QUIET));
        try {
            parser.setEncoding(encoding);
        } catch (ParserException e) {
            e.printStackTrace();
        }
    }

    public HierPathFilter(ConfigModel configModel, String htmlText) {
        this.configModel = configModel;
        this.parseText = htmlText;
        createParser(htmlText);
    }

    private void resetInputHtml() {
        try {
            parser.setInputHTML(this.parseText);
        } catch (ParserException ex) {
            Logger.getLogger(HierPathFilter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /*把路径匹配的内容过滤出来*/
    public NodeList filt(List<String> pathList) {

        NodeList list = null;
        for (int i = 0; i < pathList.size(); i++) {
            //文本节点匹配过滤
            NodeFilter filter = new RegFilterImpl(pathList.get(i));
            try {
                list = parser.extractAllNodesThatMatch(filter);    //获得
                contentFilted = list.toHtml();
                parser.setInputHTML(contentFilted);
                if (contentFilted.trim().equals("")) {
                }
            } catch (ParserException ex) {
            }
        }
        return list;
    }

    /* 其中index代表节点的次序位置 */
    public String filtContent(List<String> pathList, int index) {

        resetInputHtml();
        NodeList list = filt(pathList);
        Node tag = list.elementAt(index);
        String result = tag.toPlainTextString();//getText()
        return result;
    }

    public String filtContent(List<String> pathList, int index, String classPath) {

        resetInputHtml();
        NodeList list = filt(pathList);
        Node tag = list.elementAt(index);
        String result = "";
        if (classPath.equals("org.lt.cj.core.filters.LinkTagCustomFilter")) {
            ICustomFilter tagFilter = new LinkTagCustomFilter("UTF-8");
            result = tagFilter.customFilt(tag.toHtml());
        } else if (classPath.equals("org.lt.cj.core.filters.DivTagCustomFilter")) {
            ICustomFilter tagFilter = new DivTagCustomFilter("UTF-8");
            result = tagFilter.customFilt(tag.toHtml());
        }
        return result;
    }


    /* 其中index代表节点的次序位置 */
    public List<String> filtContents(List<String> pathList, int index) {

        resetInputHtml();
        NodeList list = filt(pathList);
        List<String> contentList = new ArrayList();
        //选择抽出类型为只抽出偶数的节点,比如0，2，4 etc
        if (index == FilterConstans.contentsEven) {
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    if ((i * 2) < list.size()) {
                        contentList.add(list.elementAt(i * 2).toPlainTextString());
                    }
                }
            }
        } else if (index == FilterConstans.contentsEvery) {//选择抽出类型为每个节点
        }
        return contentList;
    }

    public List<String> filtPhoto(List<String> pathList, int type) {

        String phofilePath = FilterConstans.filepath + new Date().getTime();
        File storeFile = new File(phofilePath);
        resetInputHtml();
        NodeList list = filt(pathList);
        List<String> photoPathsList = new ArrayList();
        //选择抽出类型为只抽出偶数的节点,比如0，2，4 etc
        storeFile.mkdirs();
        if (type == FilterConstans.contentsEven) {
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    if ((i * 2) < list.size()) {
                        ImageTag imageTag = (ImageTag) list.elementAt(i * 2);
                        HttpAccesser access = HttpAccesser.getInstance();
                        String filePath = access.downloadPhoto(phofilePath, imageTag.getAttribute("src"));
                        photoPathsList.add(filePath);
                    }
                }
            }
        } else if (type == FilterConstans.contentsEvery) {
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    ImageTag imageTag = (ImageTag) list.elementAt(i);
                    HttpAccesser access = HttpAccesser.getInstance();
                    String filePath = access.downloadPhoto(phofilePath, imageTag.getAttribute("src"));
                    photoPathsList.add(filePath);
                }
            }
        }
        return photoPathsList;
    }

    public List<String> filtScript(List<String> pathList, int index) {
        String phofilePath = FilterConstans.filepath + new Date().getTime();
        File storeFile = new File(phofilePath);
        resetInputHtml();
        NodeList list = filt(pathList);
        List<String> scriptList = new ArrayList();
        //选择抽出类型为只抽出偶数的节点,比如0，2，4 etc
        storeFile.mkdirs();
        if (index == FilterConstans.contentsEven) {
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    if ((i * 2) < list.size()) {
                        ScriptTag scriptTag = (ScriptTag) list.elementAt(index);
                        HttpAccesser access = HttpAccesser.getInstance();
                        String filePath = access.downloadPhoto(phofilePath, scriptTag.getAttribute("src"));
                        scriptList.add(filePath);
                    }
                }
            }
        } else if (index == FilterConstans.contentPointed) {
            if (list != null) {

                ScriptTag scriptTag = (ScriptTag) list.elementAt(index);
                String scriptContent = scriptTag.toPlainTextString();
                scriptList.add(scriptContent);
            }
        } else if (index == FilterConstans.contentsEvery) {
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    ImageTag imageTag = (ImageTag) list.elementAt(index);
                    HttpAccesser access = HttpAccesser.getInstance();
                    String filePath = access.downloadPhoto(phofilePath, imageTag.getAttribute("src"));
                    scriptList.add(filePath);
                }
            }
        }
        return scriptList;
    }

    public List<String> filtScript(List<String> pathList, int type, int index) {
        String phofilePath = FilterConstans.filepath + new Date().getTime();
        File storeFile = new File(phofilePath);
        resetInputHtml();
        NodeList list = filt(pathList);
        List<String> scriptList = new ArrayList();
        CustomFilter customFilter = new CustomFilter();
        //选择抽出类型为只抽出偶数的节点,比如0，2，4 etc
        storeFile.mkdirs();
        if (type == FilterConstans.contentsEven) {
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    if ((i * 2) < list.size()) {
                        ScriptTag scriptTag = (ScriptTag) list.elementAt(index);
                        HttpAccesser access = HttpAccesser.getInstance();
                        String filePath = access.downloadPhoto(phofilePath, scriptTag.getAttribute("src"));
                        scriptList.add(filePath);
                    }
                }
            }
        } else if (type == FilterConstans.contentPointed) {
            if (list != null) {

                ScriptTag scriptTag = (ScriptTag) list.elementAt(index);
                String scriptContent = scriptTag.toPlainTextString();
                customFilter.setText(scriptContent);
                scriptList = customFilter.filt();
            }
        } else if (type == FilterConstans.contentsEvery) {
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    ImageTag imageTag = (ImageTag) list.elementAt(i);
                    HttpAccesser access = HttpAccesser.getInstance();
                    String filePath = access.downloadPhoto(phofilePath, imageTag.getAttribute("src"));
                    scriptList.add(filePath);
                }
            }
        }
        return scriptList;
    }
}
